package com.promote.algorithm;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName GenerateParenthesis
 * Description 括号生成
 * @Author LiZiHao
 * Date 2023/5/15 16:14
 * @Version 1.0
 **/
public class GenerateParenthesis {
    //回溯算法
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, new StringBuilder(), 0, 0, n);
        return list;
    }

    public void backtrack(List<String> res, StringBuilder cur, int open, int close, int max) {
        if (cur.length() == max * 2) {
            res.add(cur.toString());
            return;
        }
        if (open < max) {
            cur.append('(');
            backtrack(res, cur, open + 1, close, max);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (close < open) {
            cur.append(')');
            backtrack(res, cur, open, close + 1, max);
            cur.deleteCharAt(cur.length() - 1);
        }
    }
}
